package com.company.jee.common.utilities;

import java.io.Serializable;
import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class JMSSender {

	private static Queue queue;
	private static QueueConnectionFactory queueConnectionFactory;

	public static void sendMessage(Serializable ser) 
	{
		QueueConnection connection = null;
		QueueSession session = null;
		QueueSender sender = null;
		
		try {

			try 
			{
				Properties properties = new Properties();
				properties.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
				properties.put("java.naming.factory.url.pkgs", "=org.jboss.naming:org.jnp.interfaces");
				properties.put("java.naming.provider.url", "localhost:1099");

				InitialContext ctx = new InitialContext(properties);
				queue = (Queue) ctx.lookup("queue/message");
				queueConnectionFactory = (QueueConnectionFactory) ctx
						.lookup("UIL2ConnectionFactory");
			} catch (NamingException e) 
			{
				e.printStackTrace();
			}

			connection = queueConnectionFactory.createQueueConnection();
			session = connection.createQueueSession(false,
					QueueSession.AUTO_ACKNOWLEDGE);
			sender = session.createSender(queue);
			
			
			ObjectMessage msg = session.createObjectMessage();
			msg.setObject(ser);
			
			sender.send(msg);

		} catch (JMSException e) {
			e.printStackTrace();
		} finally {

			try {
				if (connection != null) {
					sender.close();
					session.close();
					connection.close();
				}
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}

	}
}
